package com.doge.controller;


import com.doge.bean.auth.AdminLoginData;
import com.doge.bean.auth.InfoData;
import com.doge.bean.auth.MarketToken;
import com.doge.bean.auth.UserLoginData;
import com.doge.bean.base.BaseRespVo;
import com.doge.bean.auth.WxRegisterBO;
import com.doge.exception.Login501Exception;
import com.doge.service.auth.AuthService;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
public class AuthController {
    @Autowired
    AuthService authService;

    @PostMapping("admin/auth/login")
    public BaseRespVo loginAdmin(@RequestBody MarketToken token) {
        // 在 service 处理：用户登录，获取avatar，获取 sessionId
        AdminLoginData data = authService.loginAdmin(token);
        return BaseRespVo.ok(data);
    }

    @PostMapping("wx/auth/login")
    public BaseRespVo loginWx(@RequestBody MarketToken token) {
        UserLoginData data = authService.loginWx(token);
        return BaseRespVo.ok(data);
    }

    @RequestMapping("admin/auth/info")
    public BaseRespVo infoAdmin(String token) {
        // token值其实不需要，跟 x-cskaoyanmarket-admin-token 请求头是一样的
        InfoData infoData = authService.getAdminInfo(token);
        return BaseRespVo.ok(infoData);
    }

    @PostMapping({"admin/auth/logout","wx/auth/logout"})
    public BaseRespVo logout() {
        // logout, 清除session，退出
        SecurityUtils.getSubject().logout();
        return BaseRespVo.ok();
    }

    @PostMapping("wx/auth/regCaptcha")
    public BaseRespVo regapthca(@RequestBody Map map){
        String mobile = (String) map.get("mobile");
        authService.getVerfCode(mobile);
        return BaseRespVo.ok();
    }

    @PostMapping("wx/auth/register")
    public BaseRespVo register(@RequestBody WxRegisterBO bo){
        UserLoginData data = authService.register(bo);
        return BaseRespVo.ok(data);
    }

    @PostMapping("wx/auth/reset")
    public BaseRespVo reset(@RequestBody WxRegisterBO bo){
        authService.reset(bo);
        return BaseRespVo.ok();
    }

    @SneakyThrows
    @RequestMapping("/unauthc")
    public BaseRespVo unauthc(){
        // 所有未登录而访问 需要认证 的请求最终都指向这里
        System.out.println("需要登陆！");
//        return BaseRespVo.error(501,"请登录！");
        throw new Login501Exception("请登录");
    }

}

